import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:linphone_flutter_example/chat/chat_view.dart';
import 'package:linphone_flutter_example/global.dart';
import 'package:linphone_flutter_example/login.dart';
import 'package:linphone_flutter_example/phone/incoming.dart';
import 'package:linphone_flutter_example/phone_view_model.dart';
import 'package:linphone_flutter_example/phone/voice_phone.dart';
import 'package:provider/provider.dart';

void main() async {
  Global.init();
  runApp(MultiProvider(providers: [
    ChangeNotifierProvider(create: (_) => PhoneViewModel()),
  ], child: const MyApp()));
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        navigatorKey: Global.navKey,
        onGenerateRoute: HangHangRoute.generate,
        initialRoute: '/',
        builder: EasyLoading.init());
  }
}

class HangHangRoute {
  static final _routes = {
    '/': (context, {args}) => const Home(),
    'voice_phone': (context, {args}) => const VoicePhone(),
    'incoming': (context, {args}) => const Incoming(),
    'chat': (context, {args}) => const ChatView(),
    'login': (context, {args}) => const Login(),
  };

  static Route? generate(settings) {
    final Function builder = HangHangRoute._routes[settings.name] as Function;
    return MaterialPageRoute(
        settings: settings,
        builder: (context) => builder(context, args: settings.arguments));
  }
}

class Home extends StatefulWidget {
  const Home({Key? key}) : super(key: key);

  @override
  State<Home> createState() => _HomeState();
}

class _HomeState extends State<Home> {
  @override
  Widget build(BuildContext context) {
    return Consumer<PhoneViewModel>(builder: (_, model, child) {
      if (model.isConnected) {
        return const FuncList();
      } else {
        return const Login();
      }
    });
  }
}

class FuncList extends StatelessWidget {
  const FuncList({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
            actions: [IconButton(onPressed: (){
          context.read<PhoneViewModel>().delete();
        }, icon: const Icon(Icons.exit_to_app))]),
        body: Column(children: [
      ListTile(
          onTap: () {
            Navigator.pushNamed(context, "voice_phone");
          },
          title: const Text("Voip")),
      const Divider(),
      ListTile(
          onTap: () {
            Navigator.pushNamed(context, "chat");
          },
          title: const Text("IM")),
    ]));
  }
}
